﻿using AutoMapper;
using B.S.Databasic.Api.Wrter.Application.Command.Account;
using B.S.Databasic.Domain.RBAC;
using B.S.Databasic.ErrorCode;
using B.S.Databasic.Infrastructure.Interface;
using MediatR;
using System.Transactions;
using Yitter.IdGenerator;

namespace B.S.Databasic.Api.Wrter.Application.Handler.Account
{
    public class DeleleAccountHandler : IRequestHandler<DeleteAccountCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<AccountModel> accountRepo;
        private readonly IBaseRepository<RoleModel> roleRepo;
        private readonly IBaseRepository<AccountRoleModel> accountroleRepo;
        private readonly IMapper mapper;
        private readonly ILogger<DeleleAccountHandler> logger;

        public DeleleAccountHandler(IBaseRepository<AccountModel> accountRepo,
            IBaseRepository<RoleModel> roleRepo,
            IBaseRepository<AccountRoleModel> accountroleRepo,
            IMapper mapper,
            ILogger<DeleleAccountHandler> logger)
        {
            this.accountRepo = accountRepo;
            this.roleRepo = roleRepo;
            this.accountroleRepo = accountroleRepo;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="request">命令</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回统一包装类</returns>
        public async Task<ApiResult<int>> Handle(DeleteAccountCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<int>();
            try
            {
                var acc = accountRepo.GetAll().Where(x => !x.IsDeleted && x.Id == request.AccountId).FirstOrDefault();
                if (acc == null)
                {
                    res.Msg = "该用户不存在";
                    res.Code = ApiEnum.Fail;
                    return await Task.FromResult(res);
                }
                acc.IsDeleted = true;
                int r = await accountRepo.UpdateAsync(acc);
                int r1 = 0;
                var accrole = accountroleRepo.GetAll().Where(x => x.AccountId == acc.Id).ToList();
                foreach (var item in accrole)
                {
                    var roles = await roleRepo.GetValue(item.RoleId);
                    if (roles == null)
                    {
                        res.Msg = "无正确角色信息";
                        res.Code = ApiEnum.Fail;
                        return await Task.FromResult(res);
                    }
                    item.IsDeleted = true;
                    r += await accountroleRepo.UpdateAsync(item);
                }
                if (r + r1 > 0)
                {
                    res.Data = r + r1;
                    res.Msg = "删除用户成功";
                    res.Code = ApiEnum.Success;
                }
                else
                {
                    res.Data = r + r1;
                    res.Msg = "删除用户失败";
                    res.Code = ApiEnum.Fail;
                }
                logger.LogInformation($"删除用户{acc.Name}成功");
                return await Task.FromResult(res);
            }
            catch (Exception ex)
            {
                logger.LogError("删除用户异常:" + ex.Message);
                res.Msg = "删除用户异常:" + ex.Message;
                res.Code = ApiEnum.Error;
                return await Task.FromResult(res);
            }
        }
    }
}
